<?php


class OopSwoole{
    public $server = null;
    public $listen1 = null;

    public $eventList = [
        'request'=>'onRequest',
    ];

    public $config = [
        'worker_num'=>4
    ];

    public function __construct($host,$port)
    {
        $this->server = new \Swoole\Http\Server($host,$port);
    }

    public function set($configName,$configValue)
    {
        $this->config[$configName] = $configValue;
    }

    public function addListen($host, $port,$type = SWOOLE_SOCK_TCP)
    {
        $this->listen1 = $this->server->addListener($host,$port,$type);
        // 此处不设置监听1进程数量http请求此端口会调用http的回调函数 onRequest
        $this->listen1->set(
            [
                'worker_num'=>1
            ]
        );
    }

    /**
     * 处理监听
     */
    public function onReceive($serv, $fd, $from_id, $data)
    {
        $data = json_decode($data,true);
        $res_message = '';
        if($data['order_id'] == 1){
            $res_message = '订单1的信息';
        }elseif ($data['order_id'] == 2){
            $res_message = '订单2的信息';
        }else{
            $res_message = '没有找到此订单ID数据';
        }

        $serv->send($fd,$res_message);
    }

    public function onRequest(\Swoole\Http\Request $request,\Swoole\Http\Response $response)
    {

        if ($request->server['path_info'] == '/favicon.ico' || $request->server['request_uri'] == '/favicon.ico') {
            $response->end();
            return;
        }

        $goods_info = $this->getGoods("127.0.0.1","8502",['goods_id'=>1]);

        $response->header("Content-Type", "text/html; charset=utf-8");
        $response->end("获取到的商品数据为：  $goods_info");
    }


    public function getGoods($host, $port, $data)
    {
        $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
        if (!$client->connect($host, $port, 0.5))
        {
            echo "连接失败: {$client->errCode}\n";
        }
        // 此处$data 可以data传递方法（路由），rpc服务端根据方法（路由），决定调用哪个方法
        $client->send(json_encode($data,256));
        $result =  $client->recv();
        $client->close();
        return $result;

    }

    public function start(){

        if($this->listen1){
            $this->listen1->on('receive',[$this,'onReceive']);
        }

        $this->server->set($this->config);
        foreach ($this->eventList as $eventName=>$functionName){
            $this->server->on($eventName,[$this,$functionName]);
        }


        $this->server->start();
    }


}

$oopServer = new OopSwoole('0.0.0.0','9501');
$oopServer->addListen('127.0.0.1','9502');
$oopServer->start();
